package com.hancher.gamelife2.weather;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.javautil.DateUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.javautil.GsonUtil;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/7/27 18:45 <br/>
 * 描述 : 天气
 */
public class WeatherForestCnApi {
    public static String WEATHER_CN4_TODAY = "http://forecast.weather.com.cn/town/weather1dn/%s.shtml";
    public static String WEATHER_CN4_DAY7 = "http://forecast.weather.com.cn/town/weathern/%s.shtml";
    public static String WEATHER_CN4_DAY15 = "http://forecast.weather.com.cn/town/weather15dn/%s.shtml";

    /**
     * 必须在异步中执行
     *
     * @param cityCode 3级或4级城市编码
     * @return
     */
    public static WeatherAllBean queryCity4Weather(String cityCode) {
        String subCityCode = cityCode.substring(0, cityCode.length() - 3);

        WeatherAllBean weatherAllBean = new WeatherAllBean();
        queryCity4Day1(cityCode, weatherAllBean);
        queryCity4Day7(cityCode, weatherAllBean);
        queryCity4Day15(cityCode, weatherAllBean);
        boolean isCity3 = false;
        if (EmptyUtil.isEmpty(weatherAllBean.getWeatherNow().getWeather())) {
            queryCity4Day1(subCityCode, weatherAllBean);
            isCity3 = true;
        }
        if (EmptyUtil.isEmpty(weatherAllBean.getWeatherDays())) {
            queryCity4Day7(subCityCode, weatherAllBean);
            queryCity4Day15(subCityCode, weatherAllBean);
            isCity3 = true;
        }
        if (isCity3) {
            weatherAllBean.setCityCode(subCityCode);
        } else {
            weatherAllBean.setCityCode(cityCode);
        }
        return weatherAllBean;
    }

    private static void queryCity4Day15(String cityCode, WeatherAllBean weatherAllBean) {
        try {
            Connection.Response response3 = Jsoup.connect(String.format(WEATHER_CN4_DAY15, cityCode))
                    .ignoreContentType(true)
                    .execute();
            Document d3 = response3.parse();
            String tmp, tmp1, tmp2;
            Gson gson = new Gson();
            Elements scrips3 = d3.body().getElementsByTag("script");
            for (int scripsi = 0; scripsi < scrips3.size(); scripsi++) {
                tmp = scrips3.get(scripsi).html().trim();
                if (tmp.contains("var fifDay =")) {
                    tmp1 = tmp.substring(tmp.indexOf("var fifDay =") + "var fifDay =".length(), tmp.indexOf(";")).trim();
                    tmp2 = tmp.substring(tmp.indexOf("var fifNight =") + "var fifNight =".length(), tmp.lastIndexOf(";")).trim();
                    tmp1 = tmp1.replace("\"", "");
                    tmp2 = tmp2.replace("\"", "");
                    Type type = new TypeToken<ArrayList<Integer>>() {
                    }.getType();
                    ArrayList<Integer> data1 = gson.fromJson(tmp1, type);
                    ArrayList<Integer> data2 = gson.fromJson(tmp2, type);
                    for (int i = 0; i < data1.size(); i++) {
                        if (weatherAllBean.getWeatherDays().size() < i + 9) {
                            weatherAllBean.getWeatherDays().add(new WeatherDay());
                        }
                        weatherAllBean.getWeatherDays().get(i + 8)
                                .setTime(DateUtil.getRelativeMMdd(i + 7))
                                .setMaxTemp(data1.get(i).toString())
                                .setMinTemp(data2.get(i).toString());
                    }
                }
            }

            Elements e = d3.getElementsByAttributeValueContaining("class", "blue-container");
            Elements e2 = e.get(0).getElementsByAttributeValueContaining("class", "blue-item");
            for (int i = 0; i < e2.size(); i++) {
                Elements e3 = e2.get(i).getElementsByAttributeValueContaining("class", "item-icon d");
                Elements e4 = e2.get(i).getElementsByAttributeValueContaining("class", "item-icon n");
                weatherAllBean.getWeatherDays().get(i + 8).setWeatherDay(e3.get(0).attr("title"));
                weatherAllBean.getWeatherDays().get(i + 8).setWeatherNight(e4.get(0).attr("title"));
            }
        } catch (Exception e) {
            System.out.println("err:" + e);
        }
        System.out.println("15天 温度、天气：" + GsonUtil.obj2JsonStr(weatherAllBean));
    }

    private static void queryCity4Day7(String cityCode, WeatherAllBean weatherAllBean) {
        try {
            Connection.Response response2 = Jsoup.connect(String.format(WEATHER_CN4_DAY7, cityCode))
                    .ignoreContentType(true)
                    .execute();
            Document d2 = response2.parse();
            String tmp, tmp1, tmp2;
            Gson gson = new Gson();

            // region 8天 温度
            Elements scrips2 = d2.body().getElementsByTag("script");
            for (int scripsi = 0; scripsi < scrips2.size(); scripsi++) {
                tmp = scrips2.get(scripsi).html().trim();
                if (tmp.contains("var eventDay =")) {
                    tmp1 = tmp.substring(tmp.indexOf("var eventDay =") + "var eventDay =".length(), tmp.indexOf("var eventNight =")).trim().replace(";", "");
                    tmp2 = tmp.substring(tmp.indexOf("var eventNight =") + "var eventNight =".length(), tmp.lastIndexOf(";")).trim();
                    tmp1 = tmp1.replace("\"", "");
                    tmp2 = tmp2.replace("\"", "");
                    Type type = new TypeToken<ArrayList<Integer>>() {
                    }.getType();
                    ArrayList<Integer> data1 = gson.fromJson(tmp1, type);
                    ArrayList<Integer> data2 = gson.fromJson(tmp2, type);
                    for (int i = 0; i < data1.size(); i++) {
                        if (weatherAllBean.getWeatherDays().size() < i + 1) {
                            weatherAllBean.getWeatherDays().add(new WeatherDay());
                        }
                        weatherAllBean.getWeatherDays().get(i)
                                .setTime(DateUtil.getRelativeMMdd(i - 1))
                                .setMaxTemp(data1.get(i).toString())
                                .setMinTemp(data2.get(i).toString());
                    }
                }
            }
            // endregion

            // region 8天 天气
            Elements e = d2.getElementsByAttributeValueContaining("class", "blue-container");
            Elements e2 = e.get(0).getElementsByAttributeValueContaining("class", "blue-item");
            for (int i = 0; i < e2.size(); i++) {
                Elements e3 = e2.get(i).getElementsByAttributeValueContaining("class", "item-icon d");
                Elements e4 = e2.get(i).getElementsByAttributeValueContaining("class", "item-icon n");
                weatherAllBean.getWeatherDays().get(i).setWeatherDay(e3.get(0).attr("title"));
                weatherAllBean.getWeatherDays().get(i).setWeatherNight(e4.get(0).attr("title"));
            }
            // endregion

        } catch (Exception e) {
            System.out.println("err:" + e);
        }
        System.out.println("8天 温度、天气：" + GsonUtil.obj2JsonStr(weatherAllBean));
    }

    private static void queryCity4Day1(String cityCode, WeatherAllBean weatherAllBean) {
        try {
            Connection.Response response = Jsoup.connect(String.format(WEATHER_CN4_TODAY, cityCode))
                    .ignoreContentType(true)
                    .execute();
            Document d = response.parse();
            Elements scrips = d.body().getElementsByTag("script");
            String tmp, tmp1;
            Gson gson = new Gson();

            //region 实时 天气、温度、风、湿度
            try {
                for (int scripsi = 0; scripsi < scrips.size(); scripsi++) {
                    tmp = scrips.get(scripsi).html().trim();
                    if (tmp.contains("var forecast_default =")) {
                        tmp1 = tmp.substring(tmp.indexOf("var forecast_default =") + "var forecast_default =".length(), tmp.lastIndexOf(";"));
                        City4WeatherDay1Bean1 a = gson.fromJson(tmp1, City4WeatherDay1Bean1.class);
                        weatherAllBean.getWeatherNow().setTime(DateUtil.hmStr2stamp(a.getTime()));
                        weatherAllBean.getWeatherNow().setTemp(a.getTemp() + "");
                        weatherAllBean.getWeatherNow().setWindDirect(a.getWind().substring(0, a.getWind().indexOf(" ")));
                        weatherAllBean.getWeatherNow().setWindSpeed(a.getWind().substring(a.getWind().indexOf(" ") + 1, a.getWind().indexOf("级")));
                        weatherAllBean.getWeatherNow().setHumidity(a.getHumidity() + "");
                        weatherAllBean.getWeatherNow().setWeather(a.getWeather() + "");

                        break;
                    }
                }
            } catch (Exception e) {
                LogUtil.e("实时天气 err:", e);
                System.out.println("err:" + e);
            }
            System.out.println("实时 天气、温度、风、湿度: " + GsonUtil.obj2JsonStr(weatherAllBean));
            //endregion

            //region 24小时 天气、温度、风
            try {
                for (int scripsi = 0; scripsi < scrips.size(); scripsi++) {
                    tmp = scrips.get(scripsi).html().trim();
                    if (tmp.contains("var forecast_1h =")) {
                        tmp1 = tmp.substring(tmp.indexOf("var forecast_1h =") + "var forecast_1h =".length(), tmp.indexOf(";"));
                        Type type = new TypeToken<ArrayList<City4WeatherDay1Bean2>>() {
                        }.getType();
                        ArrayList<City4WeatherDay1Bean2> a = gson.fromJson(tmp1, type);
                        Long measureTime = weatherAllBean.getWeatherNow().getTime();
                        weatherAllBean.setMeasureNowTime(measureTime);
                        boolean isNextDay = false;
                        for (int j = 0; j < a.size(); j++) {
                            if (a.get(j).getTime().equals("00")) {
                                isNextDay = true;
                            }
                            WeatherHour hour = new WeatherHour()
                                    .setWeather(a.get(j).getWeather())
                                    .setTemp(a.get(j).getTime())
                                    .setWindSpeed(a.get(j).getWindL().substring(0, a.get(j).getWindL().indexOf("级")))
                                    .setWindDirect(a.get(j).getWindD())
                                    .setPredictTime(DateUtil.hh2ddhh(a.get(j).getTime(), isNextDay ? 1 : 0));
                            weatherAllBean.getWeatherHours().add(hour);
                        }
                        break;
                    }
                }
            } catch (Exception e) {
                System.out.println("err:" + e);
            }
            System.out.println("24小时 天气、温度、风:" + GsonUtil.obj2JsonStr(weatherAllBean));
            //endregion
        } catch (Exception e) {
            System.out.println("err:" + e);
        }
    }
}
